/**
 * @fileOverview drag node out of group and remove this node from group
 * @author huangtonger@aliyun.com
 */
const Page = require('../../base/');
const Global = require('../global');
const Util = require('../util/');

// 鼠标移出方案
Page.registerBehaviour('dragOutFromGroup', diagram => {
  const graph = diagram.getGraph();
  let node;
  let group;
  let timer;
  let panNodeLeave = false;

  graph.behaviourOn('drag', ev => {
    if (!diagram.getSignal('panningItem') || panNodeLeave) {
      return;
    }
    clearTimeout(timer);
    timer = setTimeout(() => {
      const panItems = diagram.get('panItems');
      if (!panItems) {
        return;
      }
      node = panItems[0];
      group = panItems[0].getParent();
      if (node
      && panItems.length === 1
      && group
      && !ev.shape) {
        const panItemDelegation = diagram.get('panItemDelegation');
        const delegationBox = panItemDelegation.getBBox();
        const groupBox = group.getBBox();
        if (Util.rectRectCrossAlgorithm(delegationBox, groupBox)) {
          graph.update(group, {
            padding: Global.groupBackgroundPadding.map(v => {
              return v - 8;
            }),
            style: Global.dragNodeLeaveFromGroupStyle
          });
          panNodeLeave = true;
        }
      }
      if (!panNodeLeave) {
        node = undefined;
        group = undefined;
      }
    }, Global.outFromGroupDelayTime);
  });
  // 鼠标重新移入原组
  graph.behaviourOn('dragenter', ev => {
    if (!node || !group) {
      return;
    }
    if (group === ev.item) {
      graph.update(group, {
        padding: Global.groupBackgroundPadding.map(v => {
          return v + 4;
        }),
        style: Global.dragNodeHoverToGroupStyle
      });
    }
    panNodeLeave = false;
  });
  graph.on('drop', ev => {
    if (!group || !node || ev.shape) {
      return;
    }
    graph.update(node, {
      parent: undefined
    });
    graph.update(group, {
      style: undefined
    });
    resetStatus();
  });
  graph.on('dragend', () => {
    resetStatus();
  });
  graph.behaviourOn('canvas:mouseleave', () => {
    resetStatus();
  });
  function resetStatus() {
    clearTimeout(timer);
    if (group) {
      graph.update(group, {
        padding: undefined,
        style: undefined
      });
    }
    panNodeLeave = false;
    node = undefined;
    group = undefined;
  }
});
